import cloud from '@lafjs/cloud'
let data
let dbName = "class-lesson-evaluation"
const db = cloud.mongo.db

export default async function (ctx: FunctionContext) {
  data = ctx.body.data
  console.log("data", data)
  switch (ctx.body.type) {
    case "details":
      return await details()
      break;
    case "update":
      return await update()
      break;
    default:
      break;
  }
}

async function details() {
  let res = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: data
  });
  return cloud.utils.requestReturn({ data: res })
}

async function update() {
  let res = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: { classId: data.classId }
  });
  if (res && res._id) {
    await cloud.nw.db.update({
      dbName,
      whereJson: { classId: data.classId },
      dataJson: data
    });
  } else {
    await cloud.utils.addData(dbName, data)
  }
  return cloud.utils.requestReturn({ data: "" })
}